import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Space, Row, Col, Button, Tabs, Collapse, Popconfirm, message} from 'antd';
import { DoubleLeftOutlined } from '@ant-design/icons';
import CommonLoading from '@/components/CommonLoading';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import { CommonTable } from '@/pages/OrderModule/common/components/CommonTable';
import Process from './components/Process';
import { useAnchor } from '@/pages/OrderModule/common/hooks/useAnchor';
import BasicInformation from './components/BasicInformation';
import Memo from './components/Memo';
import Address from './components/Address';
import { useOrderItemColumns } from './orderItemColumns';
import { useOrderLogColumns } from './orderLogColumns';
import { useArchorList } from './archorList';
import Style from './index.module.less';
import {cloneDeep, find, findIndex } from 'lodash';
import PackageAndGiveawayTabs from '@/pages/OrderModule/common/bizcomponents/PackageAndGiveawayTabs/index.jsx';
import {useFetch} from '@/pages/OrderModule/common/hooks/useFetch.js';
import {getLogData} from './service.js';
import { searchOrderByIds } from '../../../OrderList/services.js';
import IconFont from '@/components/IconFont/index.jsx';
// import DetailGoods from '@/pages/OrderModule/orderList/components/Actions/common/OrderDetailModal/components/DetailGoods/index.jsx';
import DetailGoods from '../OrderItemDetailModal/content.jsx';
import SingleOperatorBtn from './components/SingleOperatorBtn';
import { getAllArea } from "../../../../services";
import { useNavigate } from 'react-router-dom';

const ARCHOR_LIST_MAP = {
  basicInformation: 0, // 基础信息
  memo: 1, // 备注信息
  address: 2, // 收货地址
  orderItem: 3, //订单商品
  orderLog: 4, //订单日志
  gototop: 5, //回顶部
};

const OrderDetailModal = (props) => {
  const { item: records, field = 'id', orderList = [], handleOk, handleUpdateOrderList, actions, showFooter= true } = props;

  const [item, setItem] = useState(records);
  const updateKey = useRef(0);

  const archorList = useArchorList();

	const navigate = useNavigate();

  const { orderLogColumns } = useOrderLogColumns(navigate);
  const { orderItemColumns } = useOrderItemColumns();
  const [tab, setTab] = useState(archorList[ARCHOR_LIST_MAP.basicInformation].key);
  const contentWrapperRef = useRef(null);
  const anchorItems = useRef({});
  const { currentAnchor, scrollToAnchor } = useAnchor(contentWrapperRef, anchorItems);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState([]);
  const [logSortOrder, setLogSortOrder] = useState('desc');
  const selectRowKeys = useRef([]);
  const stageParams = useRef({
    runVolumeGoods: {},//跑量商品
    execCopyOrder: false
  })
  const loadOrderIds = useRef([]);
  const [spinning, setSpinning] = useState(false);
  const { loading, data: logData, fetch: fetchLogData } = useFetch(getLogData, { orderSn: item.sn, sortType: 'asc'}, false);
  const remarkInfo = {
    flag: item.flag?.[0] || 0,
    buyerMessage: item.buyerMessage || '无备注',
    sellerRemark: item.sellerMessage,
    orderRemark: item.orderRemark,
    labelIds: item.labelList
  }
  const deliveryInfo = item.deliveryInfoList?.filter(info => info.type === 2)?.[0] || {};
  const [areaList, setAreaList] = useState([]);
  const [dynamicHeight, setHeight] = useState(380);

  useEffect(() => {
    fetchLogData({orderSn: item.sn, sortType: logSortOrder})
  }, [logSortOrder])
  useEffect(() => {
    // getAreaList();
    getOrderDataFunc(records[field], true);
    archorList.forEach((item) => {
      console.log( document.getElementById(item.key))
      anchorItems.current[item.key] = document.getElementById(item.key);
    });
    window.addEventListener('resize', computeHeightFunc);
    computeHeightFunc();
    return ()=>{
      window.removeEventListener('resize', computeHeightFunc);
    }
  }, []);

  const computeHeightFunc = () => {
    try{
      const pos = document.getElementById('detail_modal_wrapper').getBoundingClientRect();
      setHeight(pos.height - 142);
    }catch{}
  }

  	//获取省市区的数据
	const getAreaList = async () => {
		const res = await getAllArea();
		if (res.success) {
			setAreaList(res?.data || []);
		}
	};

  useEffect(()=>{
    // console.log(item,'item')
  },[item])

  const formatGoodsInfo = (item) => {
    const { skuCode, id, image, skuName, memberPrice, purchasePrice, colorSpecifications, weight, spuCode, goodsSkuMatches = [] } = item;
    const { skuId, supplierId, supplierName, supplierSpuCode } = find(goodsSkuMatches, ['isDefault', 1]) || {};//匹配供应商信息

    const goodsNum = 1, goodsPrice = memberPrice || purchasePrice || 0;
    return ({
      ...item,
      goodsCode: skuCode,
      goodsImage: image,
      goodsName: skuName,
      goodsNum,
      goodsPrice,
      amount: goodsPrice * 1000 * goodsNum / 1000,
      goodsSpec: colorSpecifications,
      goodsWeight: weight,
      isCustom: 0,
      isVipGoods: Boolean(memberPrice) ? 1 : 0,
      outStoreSku: skuCode,
      outStoreSpu: spuCode,
      spu: supplierSpuCode,
      storeId: supplierId,
      storeName: supplierName,
      goodsId: skuId,
      skuId: id,
      sysGoodsId: id,
      type: 2,//0包装 1赠品 2正常商品
    })
  }
//添加商品modal props
  const addGoodsModalProps = {
    submitCallback: (addArr) => {
      const newArr = cloneDeep(data);
      addArr.map(item=>{
        const obj = find(newArr, ['id', item.id]);
        if(!obj){
          newArr.push(formatGoodsInfo(item));
        }
      })
      setData(newArr);
      selectRowKeys.current = newArr.reduce((prev, next) => {
        return prev.concat(next.id);
      }, [])
    },
    setSelectedRows: (dataSource, rowKey) => {
      const ids = selectRowKeys.current, filterIds = [];
      dataSource.map(item => {
        const id = item[rowKey];
        if (ids?.includes(id)) {
          filterIds.push(id);
        }
      });
      return filterIds;
    },
    getInputNumberValues: (value) => { }
  }

  const currentIndex = useMemo(()=>{
    return findIndex(orderList, [field, item.id]);
  }, [item])

  //上、下一条
  const handleGo = (val) => {
    getOrderDataFunc(orderList[currentIndex + val]?.[field]);
  }

  const getOrderDataFunc = async (orderId, isInit) => {
    const id = orderId || item.id;
    loadOrderIds.current.push(id);
    setSpinning(true);
    const { data, success} = await searchOrderByIds([id]);
    setSpinning(false);
    if(success && data?.length){
      if(!isInit){
        updateKey.current += 1;
        fetchLogData({orderSn: data[0]?.sn, sortType: logSortOrder})
      }
       setItem(data[0]);
    }
  }

  const handleCloseModal = () => {
    if(stageParams.current.execCopyOrder){
      message.info('检测有复制订单，新订单载入中...');
      setSpinning(true);
      setTimeout(()=>{
        setSpinning(false);
        if(handleUpdateOrderList){
          handleUpdateOrderList?.()
        }else{
          handleOk()
        }
			}, 1000)
    }else{
      handleOk(loadOrderIds.current);
    }
  }

  const handleOperator = (bool) => {
    bool && (stageParams.current.execCopyOrder = true);
    getOrderDataFunc();
  }
  
  return (
    <div>
      <CommonModal
          title= {{ title: '添加包装或赠品' }}
          open={visible == 'addPacking'}
          width = {800}
          onOk= {()=>{
            const newArr = cloneDeep(data);
            stageParams.current.packageSource.map(item=>{
              const obj = find(newArr, ['id', item.id]);
              if(!obj){
                const { goodsCommonid, goodsId, goodsPrice  } = item;
                newArr.push({
                  ...item,
                  goodsNum: item.goodsNum || 1,
                  type: stageParams.current.goodsType == 1 || 0,
                  goodsCode: goodsId,
                  amount: goodsPrice * 1000 * (item.goodsNum || 1) / 1000,
                  isCustom: 0,
                  isVipGoods: 0,
                  outStoreSku: goodsId,
                  outStoreSpu: goodsCommonid,
                });
              }
            })
            setData(newArr);
            setVisible(false);
          }}
          onCancel={()=>setVisible(false)}
      >
        <PackageAndGiveawayTabs
            onSelectionChange={(list)=>{stageParams.current.packageSource = list;} }
            changeTab={type => {stageParams.current.goodsType = type;}}
        />;
      </CommonModal>
      <CommonModal
        title={{ title: '订单详情' }}
        open={true}
        width="1360px"
        onCancel={handleCloseModal}
        maskClosable={true}
        footer={null}
        noPadding={true}
        zIndex={700}
        specWrapperStyle={{padding: '0 12px 6px 24px'}}
        maxHeight='75vh'
      >
        <div className={Style.flexBox} >
          <div className={Style.flexTitle}>
          <Process status={item.state} errorInfoList={item.errorInfoList} />
            <div className={Style.archor_tab + ' rule-reset'}>
              <Tabs
                activeKey={tab}
                onChange={(val) => {
                  if (val === 'gototop') {
                    val = archorList[ARCHOR_LIST_MAP.basicInformation].key;
                  }
                  setTab(val);
                  scrollToAnchor(val);
                }}
                items={archorList.map((item) => (
                    {
                      label: item.title,
                      key: item.key
                    }
                ))}
              >
              </Tabs>
            </div>
          </div>
          <div className={Style.contentWrapper} ref={contentWrapperRef}>
            <div className={Style.mainContent}>

                    {/* <div className={Style.detail_inner} ref={contentWrapperRef}> */}
          <Collapse
            defaultActiveKey={['basicInformation', 'memo', 'address', 'orderItem', 'orderLog']}
            ghost
            expandIcon={({ isActive }) => <DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: '16px', color: '#4E5969' }} />}
            expandIconPosition="end"
            className={Style['reset-collapse']}
          >
            <Collapse.Panel header={archorList[ARCHOR_LIST_MAP.basicInformation].render()} key="basicInformation">
              <BasicInformation item={item} />
            </Collapse.Panel>
            <Collapse.Panel header={archorList[ARCHOR_LIST_MAP.memo].render()} key="memo">
              <Memo orderId={item.id} initValues={remarkInfo} handleOk={getOrderDataFunc}/>
            </Collapse.Panel>
            <Collapse.Panel header={archorList[ARCHOR_LIST_MAP.address].render()} key="address">
              <Address initValues={deliveryInfo} record={item} actions={actions}/>
            </Collapse.Panel>
            <Collapse.Panel header={archorList[ARCHOR_LIST_MAP.orderItem].render()} key="orderItem">
              <Row gutter={[10, 10]}>
                <Col span={24}>
                  <Space>
                    <DetailGoods records={item} actions={actions} key={updateKey.current} wrapperStyle={{maxWidth: '1190px'}}/>
                  </Space>
                </Col>
              </Row>
            </Collapse.Panel>
            <Collapse.Panel style={{position: 'relative'}} header={archorList[ARCHOR_LIST_MAP.orderLog].render()} key="orderLog">
              <div className={Style.float_right_sort_btn} onClick={()=>{setLogSortOrder(logSortOrder === 'asc' ? 'desc' : 'asc')}}><IconFont type={logSortOrder === 'asc' ?'iconlog-asc' : 'icona-lujing121'} /> <span style={{display:'inline-block'}}>{logSortOrder === 'asc' ? '升序' : '降序'}</span></div>
              <CommonTable columns={orderLogColumns} dataSource={logData?.data || []} loading={loading} scroll={{ y: `calc(100vh - 250px)` }} />
            </Collapse.Panel>
            <Collapse.Panel style={{ display: 'none' }} header={archorList[ARCHOR_LIST_MAP.gototop].render()} key="gototop"></Collapse.Panel>
          </Collapse>
        </div>
            <div className={Style.positionContent}>
              <div className={Style.operationWrapper}>
                {/* <div className={Style.operationSection}></div> */}
                {
                ![51, 52].includes(item.state) && (<div >
                  <SingleOperatorBtn orderList={orderList} item={item} handleOk={handleOperator} initValues={remarkInfo}/>
                </div>)
              }
              </div>
              <div className={Style.jumpBtn}>
              <Space>
              {
                showFooter ? <>
                            <Button key="prev" onClick={() => handleGo(-1)} disabled={currentIndex == 0}>上一条</Button>
                            <Button key="next" type="primary" onClick={() => handleGo(1)} disabled={currentIndex == orderList?.length - 1}>下一条</Button>
                    </>: ''
              }
            </Space>
              </div>
            </div>
          </div>
        </div>
        {/* <div className={Style.detail_modal_wrapper} key={updateKey.current} id='detail_modal_wrapper'>
        
        <div className={Style.operator_box} style={{height: dynamicHeight}}>
          {
            ![51, 52].includes(item.state) && (<div >
              <SingleOperatorBtn orderList={orderList} item={item} handleOk={handleOperator} initValues={remarkInfo}/>
            </div>)
          }
        </div>
        <div className={Style.jump_box}>
          <Space>
            <Button key="prev" onClick={() => handleGo(-1)} disabled={currentIndex == 0}>上一条</Button>
            <Button key="next" type="primary" onClick={() => handleGo(1)} disabled={currentIndex == orderList?.length - 1}>下一条</Button>
          </Space>
        </div>

        </div> */}
      </CommonModal>
      <CommonLoading loading={spinning} />
    </div>
  );
};

export default OrderDetailModal;
